def total(from, to)
  result = 0
  from.upto(to) do |num|
    if block_given?
      result += yield(num) #yield表示执行块内容
    else
      result += num
    end
  end
  result
end

puts total(1, 10)
puts total(1, 10){|num| num**2}
n = total(1, 10) do |num| # 计算1..5的平方和
  if num > 5 # 5以后的值都忽略
    next 0
  end
  num**2
end
puts n

def block_args_test
  yield()
  yield(1)
  yield(1,2,3)
end

block_args_test do |a|
  p [a]
end
puts '-'*30
block_args_test do |a,b|
  p [a, b]
end
puts '-'*30
block_args_test do |a,b,c|
  p [a,b,c]
end
puts '-'*30
block_args_test do |*a|
  p [*a]
end

hello = Proc.new do |name|
  puts "Hello, #{name}"
end
puts 'Proc块当做对象使用：'
hello.call('Ruby')
hello.call('Ruby on Rails')

def total2(from ,to, &block)
  result = 0
  from.upto(to) do |num|
    if(block)
      result += block.call(num)
    else
      result += num
    end
  end
  result
end
n = total2(1,10) do |num|
  num**2
end
puts n
puts total2(1,10)

def call_each(ary, &block)
  ary.each(&block)
end
call_each([1,3,5]) do |num|
  num *= 2
  puts num
end

def dice
  prng = Random.new
  prng.rand(1..6)
end
def dice10
  result = []
  10.times do
    result << dice
  end
  p result
end
dice10

alpha = %w(a b c d e)
p alpha
p alpha[6]
p alpha[6,0] = ['A','B'] #替换0个元素，在索引位置n前面插入元素，n大于原数组长度，补nil
p alpha # => ["a", "b", "c", "d", "e", nil, "A", "B"]
a = []
(1..10).each do |i|
  a.push(i)
end
b = a.reject{|item| item >5}
p b
p a
b = a.reject!{|item| item >5} # 等同于 a.delete_if{|item| item > 5}
p b
p a
#############
a = [1,2,3,4]
b = [2,3,5,6]
c = a | b
p c
c = a + b
p c
d = (a + b).uniq! #uniq!是具有破坏性的方法，破坏性方法效率比较高，节省内存
p d
p d.map { |item| item * 2 } # 等同于d.collection{|item| item*2}
p d.collect { |item| item*2 }
############
a = [1, 2, 3, 4, 5]
b = [100, 200, 300, 400, 500]
c = [10, 20, 30, 40, 50]
result = []
a.zip(b, c) do |a1, a2, a3|
  result << a1 + a2 + a3
end
p result

ary = Array.new(100){|i| i+1}
result = Array.new
10.times do |i|
  result << ary[10*i..(10*i+9)]
end
p result